global class SetApprovers
{
    Webservice static List<User> getUsers()
    {
        List<User> lu = new List<User>();
        for(CallidusDataSource__c[] cds : [select UserID__c, UserRoleId__c from CallidusDataSource__c]) 
        {
            for(CallidusDataSource__c c: cds)
            {
                User[] u = [select Id, Name, UserRole.Name from User where Id = :c.UserID__c and IsActive = true];
                if(u.size() > 0)
                    lu.add(u[0]);
            }
        }
        return lu;
    }

    Webservice static String saveApprovers(Approvers__c app)
    {
        Approvers__c[] approver = [select Id from Approvers__c  where Template__c = :app.Template__c and Admin__c = :UserInfo.getUserId()];
        if(approver.size() > 0)
        {
            try
            {
                delete approver;
            }
            catch(Exception e){}
        }

        try
        {
            if(app.Level1__c != null || app.Level1__c != '')
                insert app;
        }
        catch(Exception e)
        {
            return e.getMessage();
        }
        return 'success';
    }
    
    WebService static Approvers__c getApproverRecord(String templateId)
    {
        Approvers__c[] app = [select Admin__c, Template__c, Final_Approver__c, Final_Approver_Date__c, Level1__c, Level2__c, Level3__c, Level4__c, Level5__c, Level6__c, Level7__c, Level8__c, Level9__c, Level10__c, Level11__c, Level12__c, Level13__c, Level14__c, Level15__c, Level1_Due_Date__c, Level2_Due_Date__c, Level3_Due_Date__c, Level4_Due_Date__c, Level5_Due_Date__c, Level6_Due_Date__c, Level7_Due_Date__c, Level8_Due_Date__c, Level9_Due_Date__c, Level10_Due_Date__c, Level11_Due_Date__c, Level12_Due_Date__c, Level13_Due_Date__c, Level14_Due_Date__c, Level15_Due_Date__c from Approvers__c  where Template__c = :templateId and Admin__c = :UserInfo.getUserId() order by CreatedDate desc limit 1];
        if(app.size() > 0)
            return app[0];
        else 
            return null;
    }


    static testMethod void testCase() 
    {
        getApproverRecord('a0D400000020eAQ');
        getApproverRecord('a0D40000002XnAU');
        getUsers();
        Approvers__c app = new Approvers__c(Template__c = 'a0D400000020eAQ', Admin__c = '005400000011eqL');
        saveApprovers(app);
    }

}